package cc.jcizp.service;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import cc.jcizp.MergeExcel;

/**
 * Servlet implementation class MergeExcelService
 */
@WebServlet("/MergeExcelService")
@MultipartConfig
public class MergeExcelService extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MergeExcelService() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
		response.setContentType("octets/stream");
		String key = request.getParameter("key");
		String excelName = "合并"; 
		response.addHeader("Content-Disposition", "attachment;filename="+new String( excelName.getBytes("gb2312"), "ISO8859-1" )+".xls");  
		
		String file1Name = null;
		String file2Name = null;
		File file1 = null;
		File file2 = null;
		Part part1 = null;
		Part part2 = null;
        String savePath = request.getServletContext().getRealPath("/WEB-INF");
        
        //获取上传的文件集合
		Collection<Part> parts = request.getParts();
		if (parts.size()==3) {
            //Servlet3.0将multipart/form-data的POST请求封装成Part，通过Part对上传的文件进行操作。
           //Part part = parts[0];//从上传的文件集合中获取Part对象
           part1 = request.getPart("file1");//通过表单file控件(<input type="file" name="file">)的名字直接获取Part对象
           part2 = request.getPart("file2");
           //Servlet3没有提供直接获取文件名的方法,需要从请求头中解析出来
           //获取请求头，请求头的格式：form-data; name="file"; filename="snmp4j--api.zip"
           String header = part1.getHeader("content-disposition");
           //获取文件名
           file1Name = getFileName(header);  
           header = part2.getHeader("content-disposition");
           file2Name = getFileName(header);  
       }else{
    	   PrintWriter pw = response.getWriter();
    	   pw.print("文件不是2个");
    	   pw.close();
    	   return;
       }
		
		if(!((file1Name.endsWith("xls") || file1Name.endsWith("xlsx")) && (file2Name.endsWith("xls") || file2Name.endsWith("xlsx")))){
			PrintWriter pw = response.getWriter();
			pw.print("文件后缀非法");
			pw.close();
			return;
		}
		part1.write(savePath+File.separator+file1Name);
		file1 = new File(savePath+File.separator+file1Name);
		part2.write(savePath+File.separator+file2Name);
		file2 = new File(savePath+File.separator+file2Name);
		OutputStream out = response.getOutputStream(); 
		try {
			synchronized(this){
				MergeExcel.export(file1, file2, out, key);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			file1.delete();
			file2.delete();
			part1.delete();
			part2.delete();
			if(out != null){
				out.close();
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	/**
     * 根据请求头解析出文件名
     * 请求头的格式：火狐和google浏览器下：form-data; name="file"; filename="snmp4j--api.zip"
     *                 IE浏览器下：form-data; name="file"; filename="E:\snmp4j--api.zip"
     * @param header 请求头
     * @return 文件名
     */
    public String getFileName(String header) {
        /**
         * String[] tempArr1 = header.split(";");代码执行完之后，在不同的浏览器下，tempArr1数组里面的内容稍有区别
         * 火狐或者google浏览器下：tempArr1={form-data,name="file",filename="snmp4j--api.zip"}
         * IE浏览器下：tempArr1={form-data,name="file",filename="E:\snmp4j--api.zip"}
         */
        String[] tempArr1 = header.split(";");
        /**
         *火狐或者google浏览器下：tempArr2={filename,"snmp4j--api.zip"}
         *IE浏览器下：tempArr2={filename,"E:\snmp4j--api.zip"}
         */
        String[] tempArr2 = tempArr1[2].split("=");
        //获取文件名，兼容各种浏览器的写法
        String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\")+1).replaceAll("\"", "");
        return fileName;
    }

}
